import { createRouter, createWebHashHistory } from "vue-router";
import cookie from "js-cookie"
import { ElMessage } from 'element-plus';
let Index = () => import("@/views/Index.vue")

const router = createRouter({
  history: createWebHashHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: "/",
      redirect:'/index'
    },
    // 主页页面
    {
      path:"/index",
      name:"Index",
      redirect:"/index/dashboard",
      meta:{title:"主页"},
      children:[
        //  刷新
        {name:'redirect',path:"redirect/:backpath(.*)",meta:{title:""},component: ()=>import("@/views/children/Index.vue")},
        //  用户详情
        {name:'UserInfo',path:"userinfo",meta:{title:"userinfo"},component: ()=>import("@/views/admin/UserInfo.vue")},
        // 修改密码
        {name:'ModifyPassword',path:"modifypassword",meta:{title:"modifypassword"},component: ()=>import("@/views/admin/ModifyPassword.vue")}
      ],
      component: Index,
    },
    // 登录页面
    {
      path:"/login",
      name:"Login",
      component: ()=> import("@/views/Login.vue")
    },
    // 404页面
    {
      path:"/404",
      name:"404",
      component: ()=> import("@/views/404.vue")
    },
    // 错误地址跳转到404
    {
      path:"/:path(.*)+",
      redirect:"/404"
    },
  ],
});


//路由守卫
router.beforeEach((to,from,next)=>{
  if(cookie.get("token")||to.path=='/login'){
    next()
  }else{
    next({
      replace:true,
      path:"/login",
      query:{//做标记，标记是由路由守卫跳转到的登录路由页面还是本身就是登录的路由
        name:to.path
      }
    })
    ElMessage.warning('请重新登录')
  }
})

export default router;
